package com.example.broadcasttest;

import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private IntentFilter intentFilter;

    /*private NetworkChangeReceiver networkChangeReceiver;*/
    private LocalReceiver localReceiver;

    private LocalBroadcastManager localBroadcastManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        localBroadcastManager = LocalBroadcastManager.getInstance(this); //获取实例
        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 由于安卓高版本对静态广播的使用进行了一些限制，因此改为如下代码
                /*第一种做法是添加如下代码：
                    Intent intent = new Intent(MainActivity.this, MyBroadcastReceiver.class);
                  第二种做法是：
                    Intent intent = new Intent();
                    intent.setAction("com.example.broadcasttest.MY_BROADCAST");
                    intent.setPackage(getPackageName());
                    intent.setPackage("com.example.broadcasttest2");
                  第三种做法是（该方法可以在不同程序间传递有序广播）：
                    Intent intent = new Intent("com.example.broadcasttest.MY_BROADCAST");
                    if (Build.VERSION.SDK_INT >= 26) {
                        intent.addFlags(0x01000000);
                    }
                    sendOrderedBroadcast(intent, null);
                */
                Intent intent = new Intent("com.example.broadcasttest.LOCAL_BROADCAST");
                localBroadcastManager.sendBroadcast(intent); // 发送本地广播
            }
        });
        intentFilter = new IntentFilter();
        intentFilter.addAction("com.example.broadcasttest.LOCAL_BROADCAST");
        localReceiver = new LocalReceiver();
        localBroadcastManager.registerReceiver(localReceiver, intentFilter); //注册本地广播监听器
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        localBroadcastManager.unregisterReceiver(localReceiver);
    }

    class LocalReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, "received local broadcast", Toast.LENGTH_SHORT).show();
        }

    }

}